package com.towa.ninemanmorris;

import java.util.ArrayList;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class HighscoreActivity extends Activity {

	private ListView highscore;
	private Tasker tasker;
	private String player;
	private final int listSize = 10;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.highscore);
		highscore = (ListView) findViewById(R.id.highscoreList);
		tasker = new Tasker();

		player = getIntent().getExtras().getString("player");
		ArrayList<HighscoreWrapper> list = getTotalHighscore(player);		
		
		ArrayAdapter<HighscoreWrapper> adapter = new ArrayAdapter<HighscoreWrapper>(this, android.R.layout.simple_list_item_1, list);
		highscore.setAdapter(adapter);
	}
	
	private ArrayList<String> parseString(String fetcher) {
		ArrayList<String> stringList = new ArrayList<String>();
		if (!fetcher.equals("") && fetcher != null) {
			String split = fetcher.substring("getHighscoreFromName::".length());
			String[] strings = split.split(" ");
			for (int i = 0; i < strings.length; i++) {
				stringList.add(strings[i]);
			}
		}
		Log.i("C2DM", fetcher);
		return stringList;
	}
	
	private ArrayList<HighscoreWrapper> getTotalHighscore(String player) {
		ArrayList<String> sList = new GroupTasker().doInBackground("getGroups::" + player);
		HighscoreDB hdb = new HighscoreDB(this);
		hdb.open();
		ArrayList<HighscoreWrapper> hList = new ArrayList<HighscoreWrapper>();
		for (String s : sList) {
			HighscoreWrapper hsw = hdb.getGroup(s, 10);
			if (hsw != null) {
				hList.add(hsw);
			} else {
				hsw = new GroupHighscoreTasker().doInBackground("getGroupHighscore::" + s + "::" + 10);
				hdb.addOrUpdateHighscore(hsw);
				hList.add(hsw);
			}
		}
		hdb.close();
		return hList;
	}
	
	private ArrayList<String> getGroupHighscore() {
		SharedPreferences prefs = PreferenceManager  
                .getDefaultSharedPreferences(this);  
        String fetcher = prefs.getString("payload", "");
		tasker.doInBackground("groupScores::");
		return parseString(fetcher);
	}
	
	private ArrayList<String> getGroup() {
		SharedPreferences prefs = PreferenceManager  
                .getDefaultSharedPreferences(this);  
        String fetcher = prefs.getString("payload", "");
		tasker.doInBackground("group::");
		return parseString(fetcher);
	}
	
}
